#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户角色申请模型
"""

from backend.infrastructure.database import db
from datetime import datetime

class RoleApplication(db.Model):
    """用户角色申请表"""
    __tablename__ = 'role_applications'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'), nullable=False)
    reason = db.Column(db.Text, comment='申请理由')
    attachments = db.Column(db.Text, comment='附件路径（JSON格式）')
    status = db.Column(db.String(20), default='pending', comment='申请状态：pending-待审核，approved-已通过，rejected-已拒绝')
    reviewer_id = db.Column(db.Integer, db.ForeignKey('users.id'), comment='审核人ID')
    review_reason = db.Column(db.Text, comment='审核意见')
    review_time = db.Column(db.DateTime, comment='审核时间')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    user = db.relationship('User', foreign_keys=[user_id], backref='role_applications')
    role = db.relationship('Role', backref='applications')
    reviewer = db.relationship('User', foreign_keys=[reviewer_id])
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'user_name': self.user.real_name if self.user else None,
            'role_id': self.role_id,
            'role_name': self.role.name if self.role else None,
            'role_description': self.role.description if self.role else None,
            'reason': self.reason,
            'attachments': self.attachments,
            'status': self.status,
            'reviewer_id': self.reviewer_id,
            'reviewer_name': self.reviewer.real_name if self.reviewer else None,
            'review_reason': self.review_reason,
            'review_time': self.review_time.isoformat() if self.review_time else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
